package com.vcens.yzpay.rest;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.vcens.yzpay.config.YzConfig;
import com.vcens.yzpay.model.MsgPushEntity;
import com.vcens.yzpay.service.IPayService;
import com.vcens.yzpay.socket.WebSocket;
import com.youzan.open.sdk.client.auth.Token;
import com.youzan.open.sdk.client.core.DefaultYZClient;
import com.youzan.open.sdk.client.core.YZClient;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanPayQrcodeCreateResult;
import com.youzan.open.sdk.gen.v4_0_0.api.YouzanTradeGet;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradeGetParams;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradeGetResult;
import com.youzan.open.sdk.util.hash.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLDecoder;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IPayService payService;

    @Autowired
    private YzConfig yzConfig;

    @Autowired
    private WebSocket webSocket;

    /**
     * 手动获取付款码信息
     *
     * @param payReason
     * @param amount
     * @return
     */
    @RequestMapping("/getPayCode")
    public String getPayCode(String payReason, Double amount) {
        try {
            Map<String, String> payInfo = Maps.newHashMap();
            payInfo.put("payReason", payReason);
            //有赞后台按 分 进行计算，这里 *100 代表按元计算
            payInfo.put("amount", amount * 100 + "");
            /*
                二维码类型.
                QR_TYPE_FIXED_BY_PERSON ：无金额二维码，扫码后用户需自己输入金额；
                QR_TYPE_NOLIMIT ： 确定金额二维码，可以重复支付;
                QR_TYPE_DYNAMIC：确定金额二维码，只能被支付一次
            */
            payInfo.put("qr_type", "QR_TYPE_NOLIMIT");
            //获取AccessToken
            JSONObject jsonObject = payService.getAccessToken();
            YouzanPayQrcodeCreateResult qrInfo = payService.createQrInfo(
                    new Token(jsonObject.get("access_token").toString()), payInfo);
            return JSONObject.toJSONString(qrInfo);
        } catch (Exception e) {
            logger.error("系统异常", e);
            return "系统繁忙";
        }
    }

    /**
     * 有赞交易推送接口
     *
     * @param tradeInfo
     * @return
     */
    @PostMapping(value = "/getPayPushInfo", produces = "application/json;charset=utf-8")
    public void getPayPushInfo(@RequestBody MsgPushEntity tradeInfo) {
        try {
            if (tradeInfo != null) {
                /**
                 *  判断是否为心跳检查消息
                 *  1.是则直接返回
                 */
                if (tradeInfo.isTest()) {
                    logger.error("心跳检查");
                    return;
                }
                /**
                 * 判断消息是否合法
                 * 解析sign
                 * MD5 工具类开发者可以自行引入
                 */
                String sign = MD5Utils.MD5(yzConfig.getClientId() + tradeInfo.getMsg() + yzConfig.getClientSecret());
                if (!sign.equals(tradeInfo.getSign())) {
                    logger.error("验签失败", sign);
                    return;
                }
                /**
                 * 返回结果
                 */
                //通知前台改变状态
                Map<String, Object> result = Maps.newHashMap();
                result.put("code", 200);
                result.put("status", tradeInfo.getStatus());
                result.put("msg", "请求成功");
                //推送通知
                webSocket.sendMessage(JSONObject.toJSONString(result));
                System.out.println(JSONObject.toJSONString(result));
            } else {
                throw new Exception("交易信息为null");
            }
        } catch (Exception e) {
            logger.error("系统异常", e);
        }
    }
}
